'''
Author: gigawing
Date: 2023-02-23 12:48:36
LastEditors: gigawing
LastEditTime: 2023-02-26 16:08:37
Description: 用于处理log文件，解析指定的指令记录，获取指定的位置信息数据
'''
import socket
import argparse
import re
from datetime import datetime
import time
import pandas as pd
import json

class ParseLog(object):
    def __init__(self, fileName, onLine) -> None:
        self.fileName_ = fileName
        self.onLine_ = onLine
        self.from_line = 0
        self.to_line = 0
        pass

    def ParseLimit(self, from_line, to_line):
        self.from_line = from_line
        self.to_line = to_line
        self.Parse()
        pass

    def Parse(self):
        file = open(self.fileName_, mode='r', encoding='gb2312')

        lines = []
        try:
            lines = file.readlines()
        finally:
            file.close()

        line_num = 0
        for line in lines:
            line_num += 1
            if self.from_line != 0 and self.to_line != 0 and (line_num < self.from_line or line_num > self.to_line):
                continue

            if line.find('发送记录') != -1:
                self.onLine_(line, line_num)


class PrintLog (object):
    def __init__(self) -> None:
        pass

    def online(self, line, line_num):

        print(str(line_num) + ':' + line)


class RecordLog (object):
    def __init__(self, filename, id) -> None:
        self.patten = re.compile(
            r'^<(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+).(\d+)>')
        self.filename_ = filename
        
        self.data_ = pd.DataFrame()
        self.id_ = id
        pass

    def save(self):
        print("aaa")
        self.data_.to_csv(self.filename_)
        pass

    def online(self, line, line_num):
        if (line == ''):
            return

        m = self.patten.match(line)
        if m != None:
            # print(m.group(0))
            # print(m.group(1))
            # print(m.group(2))
            now_time = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)),
                                int(m.group(4)), int(m.group(5)), int(m.group(6)), int(m.group(7)))

            command_value = line[44:]
            print(str(line_num) + ":" + str(now_time))

            data = json.loads(command_value) 

            if isinstance(data,list):   
                for item in data:
                    if item["id"] == self.id_:
                        # print("build dataframe")
                        item["time"] = now_time
                        nd = pd.DataFrame(item,index=["time"])
                        # print(nd)
                        self.data_= self.data_.append(nd)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='处理log文件，按id提取位置信息.')
    parser.add_argument('-f', action='store', help='解析的文件名', required=True)
    parser.add_argument('-o', help='保存文件', type=str, default="output_p.csv")
    parser.add_argument('-i', help='id', required=True, type=str)
    parser.add_argument('-s', help='起始行数', required=False, type=int, default=0)
    parser.add_argument('-e', help='停止行数', required=False, type=int, default=0)
    parser.add_argument('-t', help='仅测试文件', required=False, default=None)

    # sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    results = {}
    try:
        results = parser.parse_args()
        print(results)
    except Exception as e:
        parser.print_help()

    if results.t != None:
        p = PrintLog()
        log = ParseLog(results.f, p.online)
        log.Parse()
    else:
        han = RecordLog(results.o, results.i)
        log = ParseLog(results.f, han.online)
        log.ParseLimit(results.s, results.e)
        han.save()



    # sock.close()
